package com.jarcheng.movie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jarcheng.common.common.Result;
import com.jarcheng.common.common.ResultCode;
import com.jarcheng.mbg.dao.MovieDao;
import com.jarcheng.mbg.entity.Movie;
import com.jarcheng.mbg.entity.User;
import com.jarcheng.movie.service.MovieService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MovieServiceImpl implements MovieService {
    @Autowired
    MovieDao movieDao;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override

    public Result listMovies(int start, int size, String genre) {
        PageInfo<Movie> page = (PageInfo<Movie>) redisTemplate.opsForValue().get(genre + start);
        if (page != null) {
            return Result.SUCCESS(page);
        } else {
            log.info("size:" + size);
            PageHelper.startPage(start, size, "rank");
            List<Movie> ms = movieDao.selectByGenre(genre);
            page = new PageInfo<>(ms, 5);
            redisTemplate.opsForValue().set("movies:" + genre + start, page);
            return Result.SUCCESS(page);
        }
    }

    @Override
    public Result listGenres(String bigGenre) {
        return Result.SUCCESS(movieDao.getGenres(bigGenre));
    }

    @Override
    public Result listResources(String index, String id) {
        String table = "movie_resource_" + index;

        Movie movie = movieDao.listResource(table, id);
        if (movie.getRank() != null) {
            if (movie.getRank() < 50) {

                if (SecurityUtils.getSubject().hasRole("vip")) {
                    return Result.SUCCESS(movie);
                } else return new Result<>(ResultCode.PERMISSION_VIP);
            }
        }
        return Result.SUCCESS(movie);
    }

    @Override
    public int insetMovie(Movie movie) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        movie.setUuid(user.getUuid());
        return movieDao.insertSelective(movie);
    }

    @Override
    public int deleteMovie(int id) {

        return movieDao.deleteByPrimaryKey(id);
    }

    @Override
    public int updateMovie(Movie movie) {
        return movieDao.updateByPrimaryKeySelective(movie);
    }

    @Override
    public List<Movie> getUserVideo(String uuid) {
        if (uuid.equals("")) {
            User user = (User) SecurityUtils.getSubject().getPrincipal();

            return movieDao.selectUserVideo(user.getUuid());
        } else {
            return movieDao.selectUserVideo(uuid);
        }
    }

}
